<template>
  <div class="departments">
    <el-card class="card">
      <template #header>
        <div class="head">组织结构</div>
      </template>
      <div class="other-content">
        <TreeItem :item="topInfo" :istop="true" />
        <hr>
        <el-tree :data="treeData" :props="{ label: 'name' }" default-expand-all>
          <template v-slot="{ data }">
            <TreeItem :item="data" style="width: 100%" @getData="getData" />
          </template>
        </el-tree>
      </div>
    </el-card>
    <Add :init-list="initList" @getData="getData" />
  </div>
</template>

<script>
import TreeItem from './components/TreeItem.vue'
import { companyDepartment } from '@/api/departments'
import Add from './components/Add.vue'
export default {
  components: {
    TreeItem,
    Add
  },
  data() {
    return {
      topInfo: {
        name: '江苏传智教育',
        manager: '负责人',
        id: ''
      },
      treeData: [],
      initList: []
    }
  },
  async created() {
    this.getData()
  },
  methods: {
    async getData() {
      const res = await companyDepartment()
      this.initList = res.data.depts
      this.topInfo.name = res.data.companyName
      // 传入第一层数据并赋值给treeData
      this.treeData = this.changeData(res.data.depts, '')
    },
    // arr 代表传入数组 pid 代表传入的层级条件
    changeData(arr, pid = '') {
      // 返回使用过滤器后得出的值 item等于传入的数组中的每一个对象
      return arr.filter((item) => {
        // 判断传入的每一个对象的pid是否与前面单独传入的pid一致
        if (item.pid === pid) {
          // 传入的pid一致的话就在对象中创建children，并调用这个方法，
          // 传入同样的数组和当前对象的id做为再次调用这个方法的pid
          item.children = this.changeData(arr, item.id)
          return true
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.departments {
  font-size: 14px;
  padding: 20px;
  .card {
    padding: 50px;
    .head {
      margin-left: -20px;
    }
    .other-content {
      padding: 0 50px;
    }
  }
}
</style>
